package quickAdd.client;

import com.google.gwt.user.client.ResponseTextHandler;

/**
 * Methods to do HTTP GET/POST with GData AuthSub token header.
 *
 */
public class HttpUtil
{
    /**
     * Do a GET with the authorization header...
     */
    public static native boolean doAuthorizedGet( String auth, String url, ResponseTextHandler handler)
        /*-{
    var xmlHttp = new XMLHttpRequest();
    try {
      xmlHttp.open("GET", url, true);
      xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
      xmlHttp.setRequestHeader("Authorization", "GoogleLogin auth="+auth );
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
          delete xmlHttp.onreadystatechange;
          var localHandler = handler;
          var responseText = xmlHttp.responseText;
          handler = null;
          xmlHttp = null;
          localHandler.@com.google.gwt.user.client.ResponseTextHandler::onCompletion(Ljava/lang/String;)(responseText);
        }
      };
      xmlHttp.send('');
      return true;
    }
    catch (e) {
      delete xmlHttp.onreadystatechange;
      handler = null;
      xmlHttp = null;
      return false;
    }
  }-*/;

    public static void doFormPost(
        String url, String postData, ResponseTextHandler handler)
    {
        String contentType = "application/x-www-form-urlencoded; charset=utf-8";
        doAuthorizedPost( url, contentType, null, postData, handler );
    }

    /**
     * This differs from the HTTPRequest method in that it sets the content type for form data.
     * @return
     */
    public static native boolean doAuthorizedPost(
        String url, String contentType, String auth, String postData, ResponseTextHandler handler) /*-{
    var xmlHttp = new XMLHttpRequest();
    try {
      xmlHttp.open("POST", url, true);
        xmlHttp.setRequestHeader("Authorization", "GoogleLogin auth="+auth );
      xmlHttp.setRequestHeader( "Content-Type", contentType);
      xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) {
          delete xmlHttp.onreadystatechange;
          var localHandler = handler;
          var responseText = xmlHttp.responseText;
          handler = null;
          xmlHttp = null;
          localHandler.@com.google.gwt.user.client.ResponseTextHandler::onCompletion(Ljava/lang/String;)(responseText);
        }
      };
      xmlHttp.send(postData);
      return true;
    }
    catch (e) {
      delete xmlHttp.onreadystatechange;
      handler = null;
      xmlHttp = null;
      return false;
    }
  }-*/;


}
